﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PhotoMgr.src.common;
using System.Collections;
using PhotoMgr.src.database;
using popLib;
using PhotoMgr.src.gui;
using PhotoMgr.Properties;

namespace PhotoMgr.src.common
{
    public partial class ListBase : Form
    {
        public FormAction Action { get; set; }

        public object SelectedID { get; set; }

        public object SelectedItem { get; set; }

        public List<object> DataSource { get; set; }

        public string SelectedColumnName { get; set; }

        public DataGridViewColumn[] DataColumns { get; set; }

        public SearchBox[] SearchControls { get; set; }

        public int OwnerSearchBoxIndex { get; set; } //danh cho search nguoi lap chung tu, neu co thi se gan quyen view record owner/view record cho field nay
        public SearchBox OwnerSearchBox { 
            get 
            {
                if (OwnerSearchBoxIndex == null || OwnerSearchBoxIndex < 0)
                    return null;
                else
                    return SearchControls[OwnerSearchBoxIndex];
            } 
        }

        public delegate ReturnSet SearchDelegate(int page, int itemPerPage, Hashtable searchData);

        public SearchDelegate SearchFunction { get; set; }

        public Type DetailFormType { get; set; }

        public ListBase()
        {
            InitializeComponent();

            Action = new FormAction(true);

            this.Icon = PhotoMgr.Properties.Resources.logo32;
        }

        public ListBase(string title, FormAction action)
        {
            InitializeComponent();

            Action = action;

            this.Text = title;

            this.Icon = PhotoMgr.Properties.Resources.logo32;
        }

        #region Event Functions
        private void BH_Ngoai_List_Load(object sender, EventArgs e)
        {
            FormLoad();
        }

        private void pageBar1_PageChanged(int page)
        {
            Search(page);
        }

        private void btn_select_Click(object sender, EventArgs e)
        {
            ButtonSelect();
        }

        private void btn_new_Click(object sender, EventArgs e)
        {
            ButtonNew();
        }

        private void btn_view_Click(object sender, EventArgs e)
        {
            ButtonView();
        }

        private void btn_search_Click(object sender, EventArgs e)
        {
            ButtonSearch();
        }

        private void dgv_list_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (btn_select.Visible)
            {
                ButtonSelect();
            }
            else if (btn_view.Visible)
            {
                ButtonView();
            }
        }
        #endregion

        #region Handle Functions
        public virtual void FormLoad()
        {            
            //init datagridview columns
            dgv_list.AutoGenerateColumns = false;
            Global.InitDataGridView(dgv_list, DataColumns);

            //add search control to interface
            flp_container.Controls.Remove(flp_command);
            foreach (SearchBox control in SearchControls)
            {
                flp_container.Controls.Add(control);
            }            
            flp_container.Controls.Add(flp_command);

            
            //update container'size and location
            gbx_search.Height = flp_command.Location.Y + 60;
            dgv_list.Location = new Point(dgv_list.Location.X, gbx_search.Location.Y + gbx_search.Height + 10);
            dgv_list.Height = pageBar1.Location.Y - (gbx_search.Location.Y + gbx_search.Height) - 20;

            //FormLib.UpdateControlTabIndex(flp_command.Controls, SearchControls[0]);

            UpdateFormAction();

            Search(1);
        }

        public virtual void ButtonSearch()
        {
            Search(1);
        }

        public bool updateSelectedItem()
        {
            if (dgv_list.CurrentRow == null || dgv_list.CurrentRow.Index < 0) return false;

            SelectedItem = DataSource[dgv_list.CurrentRow.Index];

            SelectedID = SelectedItem.GetType().GetProperty(SelectedColumnName).GetValue(SelectedItem, null);

            return true;
        }

        public virtual void ButtonSelect()
        {
            if (updateSelectedItem())
            {
                this.Close();
            }
        }

        public virtual void ButtonNew()
        {
            if (DetailFormType == null) return;

            ReturnSet rs = MainForm.Instance.ShowExistedWindow(DetailFormType);
            if (rs.Success)
            {
                dynamic form1 = rs.Result;
                form1.ExecuteAddNew();
                return;
            }

            dynamic form = Activator.CreateInstance(DetailFormType, new object[] { Action });
            MainForm.Instance.AddMDIChild(form);

            form.FormClosed += new FormClosedEventHandler(DetailForm_FormClosed);
        }

        void DetailForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            dynamic form = sender;

            if (form.IsDatabaseChanged)
            {
                pageBar1.RefreshData();
            }
        }

        public virtual void ButtonView()
        {
            if (!updateSelectedItem()) return;

            if (DetailFormType == null) return;

            ReturnSet rs = MainForm.Instance.ShowExistedWindow(DetailFormType);
            if (rs.Success)
            {
                dynamic form1 = rs.Result;
                form1.ExecuteViewDetail(SelectedID);
                return;
            }

            dynamic form = Activator.CreateInstance(DetailFormType, new object[] { Action, SelectedID });
            MainForm.Instance.AddMDIChild(form);
            form.FormClosed +=new FormClosedEventHandler(DetailForm_FormClosed);
        }

        public virtual void UpdateFormAction()
        {
            btn_new.Visible = Action.AddRecord;
            btn_select.Visible = Action.SelectRecord;
            btn_view.Visible = Action.ViewRecord || Action.ViewRecordOwner;

            if (OwnerSearchBox != null)
            {
                OwnerSearchBox.DataControls[0].Text = UserAccount.Instance.Username;

                if (Action.ViewRecord == false && Action.ViewRecordOwner == true)
                {
                    OwnerSearchBox.DataControls[0].Enabled = false;
                }
            }

            Global.InitListFormButton(this, btn_select, btn_search, btn_view, btn_new);            
        }

        public virtual void Search(int page)
        {
            Hashtable searchData = new Hashtable();

            Hashtable temp;

            foreach (Control control in flp_container.Controls)
            {
                if (control == flp_command) continue;

                temp = ((SearchBox)control).DataValue;

                foreach (string key in temp.Keys)
                {
                    searchData.Add(key, temp[key]);
                }
            }

            ReturnSet result = SearchFunction(page, Configuration.Instance.ItemPerPage, searchData);

            if (result.Success)
            {
                PageData pageData = (PageData)result.Result;
                pageBar1.PageSource = pageData;

                List<object> datasrc = new List<object>();

                foreach (var item in (IList)pageData.DataSource)
                {
                    datasrc.Add(item);
                }

                DataSource = datasrc;
                dgv_list.DataSource = DataSource;
            }
        }
        #endregion
    }
}
